package pl.jtb.ctl.tabory.ui.se.osgi;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

public class Activator extends AbstractUIPlugin {

    public static final String PLUGIN_ID = "pl.jtb.ctl.tabory.ui.se";

    private final static Logger logger = Logger.getLogger(Activator.class);

    private static Activator plugin;

    private final static Locale locale = Locale.getDefault();

    private static ResourceBundle resourceBundle;

    public Activator() {
        try {
            resourceBundle = ResourceBundle.getBundle("messages", locale);
        } catch (Exception e) {
            resourceBundle = null;
            logger.error(e.getMessage(), e);
        }
    }

    public void start(BundleContext context) throws Exception {
        logger.info("Starting bundle: " + context.getBundle().getSymbolicName());
        super.start(context);
        plugin = this;
    }

    public void stop(BundleContext context) throws Exception {
        logger.info("Stopping bundle: " + context.getBundle().getSymbolicName());
        plugin = null;
        super.stop(context);
    }

    public static Activator getDefault() {
        return plugin;
    }

    public static ImageDescriptor getImageDescriptor(String path) {
        return imageDescriptorFromPlugin(PLUGIN_ID, path);
    }

    public static String getMessage(final String key) {
        try {
            return resourceBundle.getString(key.trim());
        } catch (final MissingResourceException e) {
            logger.error(e.getMessage(), e);
            return '!' + key + '!';
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return '!' + key + '!';
        }
    }
}
